package com.paper.tiger.easy.rpc.s.client.client;

import com.paper.tiger.easy.rpc.core.RegisterServerMesage;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * [简要描述]:
 * [详细描述]:
 *
 * @author ZouHaiBo
 * @version 1.0, 2021/5/31 10:32
 * @since JDK 1.8
 */
public class ProxyInstance implements InvocationHandler
{


    private Class clazz;

    public ProxyInstance(Class clazz)
    {
        this.clazz = clazz;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
    {
        //

        Invoke invoke = new Invoke();
        invoke.setArgs(args);


        Class<?>[] arr = new Class[args.length];
        for (int i = 0; i < args.length; i++)
        {
            Object arg = args[i];
            arr[i] = arg.getClass();
        }

        invoke.setMethod(method.getName());
        invoke.setParamsTypes(arr);

        return invoke(invoke);

    }

    private  Object invoke(Invoke invoke)
    {
        Socket socket = null;
        ObjectInputStream inputStream = null;
        ObjectOutputStream outputStream = null;
        try
        {

            RegisterServerMesage mesage = SelectService.map.get(clazz.getName());
            invoke.setInterfaceClassName(clazz.getName());
            socket = new Socket();
            socket.connect(new InetSocketAddress(mesage.getIp(),mesage.getPort()));

            outputStream = new ObjectOutputStream(socket.getOutputStream());
            inputStream = new ObjectInputStream(socket.getInputStream());

            outputStream.writeObject(invoke);
            outputStream.flush();

            Object o = inputStream.readObject();
            return o;

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        finally
        {
            try
            {
                socket.close();
                outputStream.close();
                inputStream.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return null;
    }

}
